package com.cy.server.config;

import com.cy.server.config.security.component.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;


/**
 * @peoject: yeb
 * @description: websocket配置类
 * @author: LiShaoZhuo
 * @create: 2021-05-10 15:26
 **/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    UserDetailsService userDetailsService;
    
    /** 
    * @Description: 添加endpoint，这样在网页可以通过websocket连接服务
     * 也就是配置websocket的服务地址，并且可以指定是否使用socketJS
    * @Param:
    * @return:
    * @Author: LiShaoZhuo 
    * @Date: 2021/5/10 
    */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        
        /** 
        * @Description:
         * 1. 将/ws/ep路径设置为stamp的端点，用户连接了这个端点就可以进行websocket通讯，而且支持socketJS
         * 2. setAllowedOrigins("*")  支持跨域
         * 3. withSockJS()  支持socketJS访问
        * @Param: [registry] 
        * @return: void 
        * @Author: LiShaoZhuo 
        * @Date: 2021/5/10 
        */
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }


    /**
    * @Description: 输入通道参数配置
    * @Param:
    * @return:
    * @Author: LiShaoZhuo
    * @Date: 2021/5/10
    */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        //配置拦截器
        registration.interceptors(new ChannelInterceptor() {
            /**
            * @Description: 预发送
            * @Param: [registration]
            * @return: void
            * @Author: LiShaoZhuo
            * @Date: 2021/5/10
            */
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                //判断是否为链接
                if (StompCommand.CONNECT.equals(accessor.getCommand())){
                    //获取前端传入的token
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    //判断token是否为空
                    if (!StringUtils.isEmpty(token)){
                        //拼接token
                        String authToken = token.substring(tokenHead.length());
                        //从token中获取用户名
                        String username = jwtTokenUtil.getUserNameFromToken(authToken);
                        //判断用户名是否为空
                        if (!StringUtils.isEmpty(username)){
                            //登录
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            //验证token是否有效，重新设置用户对象
                            if (jwtTokenUtil.validateToken(authToken, userDetails)){
                                UsernamePasswordAuthenticationToken authenticationToken =
                                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                                //设置用户权限
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                //设置用户
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });
    }

    /**
     * 配置消息代理
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 配置代理域，可以配置多个，配置代理目的地前缀为/queue，可以在配置域上向客户端推送消息
        registry.enableSimpleBroker("/queue");
    }
}
